// 引入 Sequelize 类
const { Sequelize } = require('sequelize');
require('dotenv').config();

// 根据环境变量设置数据库配置
const isTestEnv = process.env.NODE_ENV === 'test';
const dbName = isTestEnv ? process.env.DB_NAME : process.env.DB_NAME;
const dbUser = isTestEnv ? process.env.DB_USER_TEST : process.env.DB_USER;
const dbPass = isTestEnv ? process.env.DB_PASS_TEST : process.env.DB_PASS;
const dbHost = isTestEnv ? process.env.DB_HOST_TEST : process.env.DB_HOST;

// 创建 Sequelize 实例
const sequelize = new Sequelize(
  process.env.DB_NAME || process.env.DB_NAME || 'flower_db',
  process.env.DB_USER_TEST || process.env.DB_USER || 'root',
  process.env.DB_PASS_TEST || process.env.DB_PASS || '123456',
  {
    host: process.env.DB_HOST_TEST || process.env.DB_HOST || 'localhost',
    dialect: 'mysql',
    logging: (msg) => {
      if (process.env.SQL_LOG === 'true') {
        console.log(msg);
      }
    },
    define: {
      // 使用下划线命名法
      underscored: true,
      // 禁用时间戳，由数据库自动管理
      timestamps: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      // 逻辑删除
      // paranoid: true,
      // deletedAt: 'deleted_at'
    },
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  }
);

module.exports = {
  sequelize
};